'''
Created on Jan 18, 2010

@author: christianp
'''
from math import ceil
from math import floor
from Extent import Extent
from TileRange import TileRange

class AxisInvertedY(object):

    def __init__(self):
        '''axisnormal'''
    
    def worldToTile(self, extent, level, schema):
        resolution = schema.resolutions[level][1]
        tileWorldUnits = resolution * schema.width
        
        firstCol = floor((extent.getMinX() - schema.origin_x) / tileWorldUnits)
        firstRow = floor((-extent.getMaxY() + schema.origin_y) / tileWorldUnits)        
        lastCol = ceil((extent.getMaxX() - schema.origin_x) / tileWorldUnits)
        lastRow = ceil((-extent.getMinY() + schema.origin_y) / tileWorldUnits)
        
        return TileRange(firstCol, firstRow, lastCol, lastRow);
    
    def worldToTile2(self, extent, resolution, schema):
        tileWorldUnits = resolution * schema.width
        
        firstCol = floor((extent.min_x - schema.origin_x) / tileWorldUnits)
        firstRow = floor((-extent.max_y + schema.origin_y) / tileWorldUnits)        
        lastCol = ceil((extent.max_x - schema.origin_x) / tileWorldUnits)
        lastRow = ceil((-extent.min_y + schema.origin_y) / tileWorldUnits)
        
        return TileRange(firstCol, firstRow, lastCol, lastRow);

    def tileToWorld(self, range, level, schema):
        resolution = schema.resolutions[level][1]
        tileWorldUnits = resolution * schema.width
        
        minX = range.getFirstCol() * tileWorldUnits + schema.origin_x
        minY = -(range.getLastRow()+1) * tileWorldUnits + schema.origin_y
        maxX = (range.getLastCol()+1) * tileWorldUnits + schema.origin_x
        maxY = -range.getFirstRow() * tileWorldUnits + schema.origin_y

        extent = Extent(minX, minY, maxX, maxY)
        return extent
    
    def tileToWorld2(self, range, resolution, schema):
        tileWorldUnits = resolution * schema.width
        
        minX = range.getFirstCol() * tileWorldUnits + schema.origin_x
        minY = -(range.getLastRow()+1) * tileWorldUnits + schema.origin_y
        maxX = (range.getLastCol()+1) * tileWorldUnits + schema.origin_x
        maxY = -range.getFirstRow() * tileWorldUnits + schema.origin_y

        extent = Extent(minX, minY, maxX, maxY)
        return extent